package com.sigmatrix.h5.service.impl;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.RandomStringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.sigmatrix.h5.dao.DisDealerAcctDao;
import com.sigmatrix.h5.dao.EnterpriseDao;
import com.sigmatrix.h5.dto.LoginData;
import com.sigmatrix.h5.entity.DisDealer;
import com.sigmatrix.h5.entity.DisDealerAcct;
import com.sigmatrix.h5.entity.DisDealerAcctRegAudit;
import com.sigmatrix.h5.entity.DisRoleRes;
import com.sigmatrix.h5.entity.DisTerminalShop;
import com.sigmatrix.h5.entity.DisTerminalShopDetail;
import com.sigmatrix.h5.entity.Enterprise;
import com.sigmatrix.h5.enums.CrmAcctType;
import com.sigmatrix.h5.enums.ResponseEnum;
import com.sigmatrix.h5.enums.UserType;
import com.sigmatrix.h5.exception.MessageException;
import com.sigmatrix.h5.exception.ServiceException;
import com.sigmatrix.h5.response.Response;
import com.sigmatrix.h5.service.DisAcctRoleService;
import com.sigmatrix.h5.service.DisDealerAcctService;
import com.sigmatrix.h5.service.DisRoleResService;
import com.sigmatrix.h5.service.DisRoleService;
import com.sigmatrix.h5.service.DisTerminalShopDetailService;
import com.sigmatrix.h5.utils.Assert;
import com.sigmatrix.h5.utils.CommonUtils;
import com.sigmatrix.h5.utils.Cons;
import com.sigmatrix.h5.utils.Constants;
import com.sigmatrix.h5.utils.MD5Utils;
import com.sigmatrix.h5.utils.SessionUtils;
import com.sigmatrix.h5.utils.Utils;
import com.sigmatrix.h5.web.vo.LoginVo;
import com.sigmatrix.sc.jdbc.common.service.ServiceImpl;

/**
 * 
 *@ClassName: DisDealersAcctServiceImpl
 *@Description: CRM账号
 *@author MH
 *@date 2017年12月18日 下午8:06:45
 */
@Service
public class DisDealerAcctServiceImpl extends ServiceImpl<DisDealerAcct, Integer> implements DisDealerAcctService{
	@Autowired
	private transient EnterpriseDao enterpriseDao;
	@Autowired
	private DisDealerAcctDao disDealerAcctDao;
	@Autowired
	private DisRoleService disRoleService;
	@Autowired
	private DisAcctRoleService disAcctRoleService;
	@Autowired
	private DisRoleResService disRoleResService;
	@Autowired
	private DisTerminalShopDetailService disTerminalShopDetailService;

	@Override
	public DisDealerAcct findByUserName(String userName) {
		DisDealerAcct acct = new DisDealerAcct();
		acct.setAccount(userName);
		return disDealerAcctDao.selectOne(acct);
	}
	@Override
	public DisRoleRes checkPermission(Integer userId, String eseCode,String moduleCode) {
		return disRoleResService.checkPremission(userId, eseCode,moduleCode);
	}
	@Override
	public DisDealerAcct save(DisDealerAcctRegAudit audit, DisDealer dealer) {
		//验证参数
		validateNotNull(audit, dealer);;
		DisDealerAcct acct = new DisDealerAcct();
		acct.setAccount(dealer.getCellPhoneNum());//账号为手机号
		acct.setAudit(Short.valueOf("1"));//1已审核，0未审核
		acct.setBasicModuleId(-1);
		acct.setContact(dealer.getCellPhoneNum());
		acct.setDealerId(dealer.getId());
		acct.setEnterpriseId(dealer.getEnterpriseId());
		acct.setName(dealer.getContact());
		acct.setOpenId(dealer.getOpenId());
		acct.setPwd(audit.getPwd());
		acct.setPromotionCode(promotionCode());
		acct.setUserType(UserType.ADMIN.value);
		acct.setStatus(Constants.STATUS_ENABLE);
		acct.setAcctType(CrmAcctType.DEALER.value);
		acct.setDealersAcctPromotionCode(audit.getPromotionCode());
		Integer id = insertSelective(acct);
		acct.setId(id);
		return acct;
	}
	private String promotionCode(){
		String promotionCode = RandomStringUtils.random(8, "0123456789");
		while(findByPromotionCode(promotionCode) != null){
			promotionCode = RandomStringUtils.random(8, "0123456789");
		}
		return promotionCode;
	}
	private void validateNotNull(DisDealerAcctRegAudit audit, DisDealer dealer){
		Assert.notNull(audit.getPwd(), "申请信息中没有密码");
		Assert.notNull(dealer.getCellPhoneNum(), "经销商信息中没有电话号码");
		Assert.notNull(dealer.getId(), "经销上信息没有主键");
		Assert.notNull(dealer.getEnterpriseId(), "经销商信息中没有企业ID");
		Assert.notNull(dealer.getContact(), "经销商信息中没有联系人姓名");
		Assert.notNull(dealer.getOpenId(), "经销商信息没有openId");
		int i = disDealerAcctDao.selectCountByAccount(dealer.getCellPhoneNum());
		if(i >0 ) throw new MessageException(String.format("手机号[%s]已经注册过", dealer.getCellPhoneNum()));
	}

	@Override
	@Transactional
	public void saveRoleInfo(Integer dealerId, Integer acctId) {
		//创建admin角色
		Integer roleId = disRoleService.createAdmin(dealerId);
		Assert.notNull(roleId, "创建角色失败");
		//把账号赋予admin角色
		Integer acctRoleId = disAcctRoleService.create(dealerId, acctId, roleId);
		Assert.notNull(acctRoleId, "账号绑定角色失败");
		//给角色授予所有权限
		disRoleResService.grantAllRes(dealerId, roleId);
	}
	@Override
	public Map<Integer, String> getDealers(Integer dealerId) {
		Map<Integer,String> map = new HashMap<Integer,String>();
		//如果用户指定了经销商，就返回指定的经销商
		if(CommonUtils.isNotEmpty(dealerId)){
			map.put(dealerId, null);
			return map;
		}
		//如果没有指定经销商，判断是经销商用户还是终端门店用户，如果是终端门店用户，就查询终端店管理过的所有经销商
		Short acctType = SessionUtils.getAcctType();
		if(CrmAcctType.TERMINAL_SHOP.value.equals(acctType)){
			Assert.notNull(SessionUtils.getTerminalShopId(), "终端店ID为空，请联系管理员");
			List<DisTerminalShopDetail> shopDetails = disTerminalShopDetailService.findByTerminalShopId(SessionUtils.getTerminalShopId());
			Assert.notNull(shopDetails, String.format("终端店[%s]没有关联过经销商", SessionUtils.getTerminalShopId()));
			for (DisTerminalShopDetail disTerminalShopDetail : shopDetails) {
				map.put(disTerminalShopDetail.getDealerId(), null);
			}
		}else if(CrmAcctType.DEALER.value.equals(acctType)){
			Assert.notNull(SessionUtils.getDealerId(), "经销商ID为空，请联系管理员");
			map.put(SessionUtils.getDealerId(), null);
		}else{
			throw new MessageException("非终端店跟经销商用户不能扫码");
		}
		return map;
	}
	@Override
	public DisDealerAcct findByPromotionCode(String promotionCode) {
		DisDealerAcct acct = new DisDealerAcct();
		acct.setPromotionCode(promotionCode);
		acct.setEnterpriseId(SessionUtils.getEseId());
		return disDealerAcctDao.selectOne(acct);
	}
	@Override
	public DisDealerAcct findSalesMan(Integer id) {
		return disDealerAcctDao.findSalesMan(id) ;
	}
	@Override
	public Integer save(DisDealerAcctRegAudit data, DisDealer dealer, DisTerminalShop shop) {
		//验证参数
		validate(data, dealer, shop);
		DisDealerAcct acct = new DisDealerAcct();
		acct.setAccount(shop.getMobilePhone());//账号为手机号
		acct.setAudit(Short.valueOf("1"));//1已审核，0未审核
		acct.setBasicModuleId(-1);
		acct.setContact(shop.getMobilePhone());
		acct.setDealerId(dealer.getId());
		acct.setEnterpriseId(dealer.getEnterpriseId());
		acct.setName(shop.getContact());
		acct.setOpenId(shop.getOpenId());
		acct.setPwd(data.getPwd());
		acct.setPromotionCode(promotionCode());
		acct.setUserType(UserType.ADMIN.value);
		acct.setStatus(Constants.STATUS_ENABLE);
		acct.setAcctType(CrmAcctType.TERMINAL_SHOP.value);
		acct.setTerminalShopId(shop.getId());
		return insertSelective(acct);
	}
	private void validate(DisDealerAcctRegAudit data, DisDealer dealer, DisTerminalShop shop) {
		Assert.notNull(data.getPwd(), "申请信息中没有密码");
		Assert.notNull(shop.getMobilePhone(), "门店信息中没有电话号码");
		Assert.notNull(shop.getId(), "门店信息没有主键");
		Assert.notNull(shop.getContact(), "门店信息中没有联系人姓名");
		int i = disDealerAcctDao.selectCountByAccount(shop.getMobilePhone());
		if(i >0 ) throw new MessageException(String.format("手机号[%s]已经注册过", shop.getMobilePhone()));
	}
	/**(non-Javadoc)
	 *@Title: checkPhone
	 *@Description:
	 *@see com.sigmatrix.h5.service.DisDealerAcctService#checkPhone(java.lang.String)
	 *@author wjwei
	 *@date 2018年3月7日 下午7:14:52
	 */
	@Override
	public boolean checkPhone(String phone) {
		int i = disDealerAcctDao.selectCountByAccount(phone);
		if(i >0 ) return false;
		else return true;
	}
	
	/**
	 * 分销app合并分支开始-------------------------------------
	 */
	
	/**(non-Javadoc)
	 *@Title: validateLogin
	 *@Description: 
	 *@see com.sigmatrix.h5.service.DisDealersAcctService#validateLogin(com.sigmatrix.h5.web.vo.LoginVo)
	 *@date 2017年8月15日 上午12:13:19
	 */
	@Override
	public Response validateLogin(LoginVo vo) throws ServiceException {
		//根据账号查询
		try {
			final DisDealerAcct dealerAcct = disDealerAcctDao.findByAcct(null, vo.getAccount());
			if(Utils.isEmpty(dealerAcct)){
				return new Response(ResponseEnum.NO_DATA,dealerAcct);
			}
			//判断状态是否为启用
			if(Cons.STATUS_ENABLE != dealerAcct.getStatus()){
				return new Response(ResponseEnum.EXCEPTION.getCode(),"账号不可用");
			}
		    //账号类型, 1-企业CRM账号,2-经销商CRM账号,3-终端门店CRM账号
			if(Cons.ACCT_TYPE_DEALER != dealerAcct.getAcctType()){
				return new Response(ResponseEnum.EXCEPTION.getCode(),"请使用经销商CRM账号");
			}
			//密码加密验证是否正确
			final String pwd = MD5Utils.getMD5Code(vo.getPwd());
			if(!pwd.equals(dealerAcct.getPwd())){
				return new Response(ResponseEnum.EXCEPTION.getCode(),"密码不正确");
			}
			
			//查询账号所属企业信息
			Enterprise enterprise = null;//企业信息
			final Integer eseId = dealerAcct.getEnterpriseId();//企业id
			if(Utils.isNotEmpty(eseId)){
				enterprise = enterpriseDao.findById(eseId);
			}
			if(Utils.isEmpty(enterprise)||Utils.isEmpty(enterprise.getCode())){
				return new Response(ResponseEnum.EXCEPTION.getCode(),"账号企业信息不存在");
			}
			//登录返回信息
			final LoginData loginData = new LoginData();
			loginData.setEnterpriseCode(enterprise.getCode());//企业code
			loginData.setUserDealerId(dealerAcct.getDealerId());//经销商id
			loginData.setUserId(dealerAcct.getId());//经销商账号id
			return new Response(ResponseEnum.SUCCESS, loginData);
		} catch (Exception e) {
			throw new ServiceException(e);
		}
	}

	 
	 /**
	 * 分销app合并分支结束-------------------------------------
	 */
	@Override
	public List<DisDealerAcct> findByOpenId(String openId) {
		DisDealerAcct acct = new DisDealerAcct();
		acct.setOpenId(openId);
		List<DisDealerAcct> list = select(acct);
		return list;
	}

}
